package com.userdemo.demo.service.base.impl;

import com.userdemo.demo.annotation.SysLog;
import com.userdemo.demo.base.BaseService;
import com.userdemo.demo.common.sys.ServerResponse;
import com.userdemo.demo.constant.base.Const;
import com.userdemo.demo.entity.base.BaseMenu;
import com.userdemo.demo.entity.base.dto.BaseMenuDTO;
import com.userdemo.demo.entity.base.vo.BaseMenuVO;
import com.userdemo.demo.entity.base.vo.BaseUserVO;
import com.userdemo.demo.enumeration.base.UseTypeEnum;
import com.userdemo.demo.enumeration.base.YesOrNoEnum;
import com.userdemo.demo.service.base.IBaseMenuService;
import com.userdemo.demo.util.base.NumberUtil;
import com.userdemo.demo.util.base.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 　　* @description: 菜单服务层
 * 　　* @param ${tags}
 * 　　* @return ${return_type}
 * 　　* @throws
 * 　　* @author 陈宇
 * 　　* @date $date$ $time$
 *
 */
@Service("iBaseMenuService")
public class BaseMenuServiceImpl extends BaseService implements IBaseMenuService {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增/更新菜单
     *
     * @param baseMenuDTO
     * @param baseUserVO
     * @return
     */
    @SysLog("新增/更新菜单")
    @Override
    public ServerResponse<String> addOrUpdateMenu(BaseMenuDTO baseMenuDTO, BaseUserVO baseUserVO) {
        if(null == baseMenuDTO || null == baseUserVO){
            return ServerResponse.createByErrorMessage("参数错误");
        }
        if(StringUtil.isEmpty(baseMenuDTO.getName()) || StringUtil.isEmpty(baseMenuDTO.getUrl())){
            return ServerResponse.createByErrorMessage("菜单名称或菜单路径不能为空");
        }
        //如果不是平台用户则判断权限
        if(baseUserVO.getUseType().intValue() != UseTypeEnum.PLATFORM.getCode()){
            //判断使用类型权限
            return ServerResponse.createByErrorMessage("无权限访问，请使用平台账户新增或修改");
        }
        BaseMenu baseMenu = null;
        boolean isAdd = false;
        if(null != baseMenuDTO.getMenuId() && 0 < baseMenuDTO.getMenuId()){
            baseMenu = baseMenuMapper.selectByPrimaryKey(baseMenuDTO.getMenuId());
            if(null == baseMenu){
                return ServerResponse.createByErrorMessage("数据错误");
            }
            baseMenu.setUpdateUser(baseUserVO.getUserName());
        }
        if(null == baseMenu){
            baseMenu = new BaseMenu();
            isAdd = true;
            baseMenu.setCreateUser(baseUserVO.getUserName());
            baseMenu.setUpdateUser(baseUserVO.getUserName());
        }
        baseMenu.setParentId(baseMenuDTO.getParentId());
        baseMenu.setUrl(baseMenuDTO.getUrl());
        baseMenu.setName(baseMenuDTO.getName());
        baseMenu.setDescInfo(baseMenuDTO.getDescInfo());
        baseMenu.setIcon(baseMenuDTO.getIcon());
        baseMenu.setOrd(baseMenuDTO.getOrd());
        baseMenu.setUseType(baseMenuDTO.getUseType());
        //删除缓存
        redisTemplate.delete(Const.TREEMENU+UseTypeEnum.PLATFORM.getCode());
        redisTemplate.delete(Const.TREEMENU+UseTypeEnum.HOSPITAL.getCode());
        redisTemplate.delete(Const.TREEMENU+UseTypeEnum.AC.getCode());
        redisTemplate.delete(Const.TREEMENU+UseTypeEnum.SUPPLIERS.getCode());
        redisTemplate.delete(baseUserVO.getUserName()+Const.BASEMENUVO);
        if(isAdd){
            baseMenu.setId(baseMenuMapper.selectSeq());
            if(baseMenuMapper.insert(baseMenu) > 0){
                return ServerResponse.createBySuccessMessage("新增成功");
            }
        }else{
            if(baseMenuMapper.updateByPrimaryKeySelective(baseMenu) > 0){
                return ServerResponse.createBySuccessMessage("更新成功");
            }
        }
        return ServerResponse.createByErrorMessage("操作失败");
    }

    /**
     * 删除菜单
     *
     * @param baseMenuDTO
     * @param baseUserVO
     * @return
     */
    @SysLog("删除菜单")
    @Override
    public ServerResponse<String> delById(BaseMenuDTO baseMenuDTO, BaseUserVO baseUserVO) {
        if(null == baseMenuDTO || null == baseUserVO || null == baseMenuDTO.getMenuId()){
            return ServerResponse.createByErrorMessage("参数错误");
        }
        //如果不是平台用户则判断权限
        if(baseUserVO.getUseType().intValue() != UseTypeEnum.PLATFORM.getCode()){
            //判断使用类型权限
            return ServerResponse.createByErrorMessage("无权限访问，请使用平台账户删除");
        }
        if(baseMenuMapper.updateMenuStatus(baseMenuDTO.getMenuId(),baseUserVO.getUserName()) > 0){
            //删除缓存
            redisTemplate.delete(Const.TREEMENU+UseTypeEnum.PLATFORM.getCode());
            redisTemplate.delete(Const.TREEMENU+UseTypeEnum.HOSPITAL.getCode());
            redisTemplate.delete(Const.TREEMENU+UseTypeEnum.AC.getCode());
            redisTemplate.delete(Const.TREEMENU+UseTypeEnum.SUPPLIERS.getCode());
            redisTemplate.delete(baseUserVO.getUserName()+Const.BASEMENUVO);
            return ServerResponse.createBySuccessMessage("删除成功");
        }
        return ServerResponse.createByErrorMessage("删除失败");
    }

    /**
     * 列表查询菜单
     *
     * @param baseMenuDTO
     * @return
     */
    @Override
    public ServerResponse<List<BaseMenuVO>> selectListMenu(BaseMenuDTO baseMenuDTO,BaseUserVO baseUserVO) {
        if(null == baseMenuDTO){
            return ServerResponse.createByErrorMessage("参数错误");
        }
        //如果不是平台用户则判断权限
        if(baseUserVO.getUseType().intValue() != UseTypeEnum.PLATFORM.getCode()){
            //判断使用类型权限
            baseMenuDTO.setUseType(baseUserVO.getUseType().toString());
        }
        List<BaseMenuVO> list = baseMenuMapper.selectListByParam(baseMenuDTO);
        if(null == list || 0 == list.size()){
            return ServerResponse.createByErrorMessage("没有数据");
        }
        return ServerResponse.createBySuccess("查询成功",list);
    }

    /**
     * 查询树状用户菜单
     *
     * @param baseUserVO
     * @return
     */
    @Override
    public ServerResponse<List<BaseMenuVO>> selectTreeMenuByUserName(BaseUserVO baseUserVO) {
        if(null == baseUserVO || StringUtil.isEmpty(baseUserVO.getUserName())){
            return ServerResponse.createByErrorMessage("参数错误");
        }
        //查询该用户是否有菜单缓存
        Object catchMenuObj =  redisTemplate.opsForValue().get(baseUserVO.getUserName()+Const.BASEMENUVO);
        if(null != catchMenuObj){
            List<BaseMenuVO> list = (List<BaseMenuVO>) catchMenuObj;
            if(null != list && 0 < list.size()){
                return ServerResponse.createBySuccess("查询成功",list);
            }
        }
        long parentId = 0;
        String useType = null;
        //如果不是平台用户则判断权限
        if(baseUserVO.getUseType().intValue() != UseTypeEnum.PLATFORM.getCode()){
            //判断使用类型权限
            useType = baseUserVO.getUseType().toString();
        }
        List<BaseMenuVO> baseMenuVOS ;
        //判断登录用户是否为供应商类型
        if(baseUserVO.getUseType().intValue() == UseTypeEnum.SUPPLIERS.getCode()){
            baseMenuVOS = getTreeMenuListByUserName(baseUserVO.getUserName(),parentId,useType,YesOrNoEnum.YES.getCode());
        }else{
            baseMenuVOS = getTreeMenuListByUserName(baseUserVO.getUserName(),parentId,useType,YesOrNoEnum.NO.getCode());
        }

        if(null == baseMenuVOS || 0 == baseMenuVOS.size()){
            return ServerResponse.createByErrorMessage("没有数据");
        }
        //存入缓存
        redisTemplate.opsForValue().set(baseUserVO.getUserName()+Const.BASEMENUVO,baseMenuVOS);
        //缓存24小时
        redisTemplate.expire(baseUserVO.getUserName()+Const.BASEMENUVO,Const.MENUCACHETIME,TimeUnit.HOURS);
        return ServerResponse.createBySuccess("查询成功",baseMenuVOS);
    }



    List<BaseMenuVO> getTreeMenuListByUserName(String userName,Long parentId,String useType,int isSuppliers){
        List<BaseMenuVO> list;
        //如果是供应商使用类型
        if(isSuppliers == YesOrNoEnum.YES.getCode()){
            //判断企业信息是否通过
            if(baseMenuMapper.selectCountCompanyByUserName(userName) == 0){
                list = baseMenuMapper.selectAuditedSuppliersMenu();
                return list;
            }else{
                list = baseMenuMapper.selectSuppliersMenu(parentId,useType);
            }
        }else {
            list = baseMenuMapper.selectByUserNameAndParentId(userName, parentId, useType);
        }
        if(null != list && 0 < list.size()){
            for (int i = 0; i < list.size(); i++) {
                list.get(i).setChildren(getTreeMenuListByUserName(userName,list.get(i).getMenuId(),useType,isSuppliers));
            }
        }
        return list;
    }

    List<BaseMenuVO> getTreeMenuList(Long parentId,String useType,String userName){
        List<BaseMenuVO> list;
        if(UseTypeEnum.SUPPLIERS.getCode() == NumberUtil.safeToNumber(useType)
        || StringUtil.isEmpty(useType)){
            list = baseMenuMapper.selectListByParentId(parentId,useType);
        }else{
            list = baseMenuMapper.selectListByParentIdAndUserName(parentId,userName,useType);
        }
        if(null != list && 0 < list.size()){
            for (int i = 0; i < list.size(); i++) {
                list.get(i).setChildren(getTreeMenuList(list.get(i).getMenuId(),useType,userName));
            }
        }
        return list;
    }


    /**
     * 查询树形所有菜单
     * @return
     */
    @Override
    public ServerResponse<List<BaseMenuVO>> selectTreeMenu(BaseUserVO baseUserVO) {
        long parentId = 0;
        String useType = null;
        if(null == baseUserVO.getUseType()){
            return ServerResponse.createByErrorMessage("用户信息错误");
        }
        //查询该用户是否有菜单缓存
        Object catchMenuObj =  redisTemplate.opsForValue().get(baseUserVO.getUserName()+Const.TREEMENU);
        if(null != catchMenuObj){
            List<BaseMenuVO> list = (List<BaseMenuVO>) catchMenuObj;
            if(null != list && 0 < list.size()){
                return ServerResponse.createBySuccess("查询成功",list);
            }
        }
        //如果不是平台用户则判断权限
        if(baseUserVO.getUseType().intValue() != UseTypeEnum.PLATFORM.getCode()){
            //判断使用类型权限
            useType = baseUserVO.getUseType().toString();
        }
        List<BaseMenuVO> list = getTreeMenuList(parentId,useType,baseUserVO.getUserName());
        if(null == list || 0 == list.size()){
            return ServerResponse.createByErrorMessage("没有数据");
        }
        redisTemplate.opsForValue().set(baseUserVO.getUserName()+Const.TREEMENU,list);
        //缓存1小时
        redisTemplate.expire(baseUserVO.getUserName()+Const.TREEMENU,Const.INITPAGENUM,TimeUnit.HOURS);
        return ServerResponse.createBySuccess("查询成功",list);
    }

    /**
     * 查询单个菜单详情
     *
     * @param baseMenuDTO
     * @return
     */
    @Override
    public ServerResponse<BaseMenuVO> selectMenuById(BaseMenuDTO baseMenuDTO,BaseUserVO baseUserVO) {
        if(null == baseMenuDTO || null == baseMenuDTO.getMenuId()){
            return ServerResponse.createByErrorMessage("参数错误");
        }
        String useType = null;
        //如果不是平台用户则判断权限
        if(baseUserVO.getUseType().intValue() != UseTypeEnum.PLATFORM.getCode()){
            //判断使用类型权限
            useType = baseUserVO.getUseType().toString();
        }
        BaseMenuVO baseMenuVO = baseMenuMapper.selectById(baseMenuDTO.getMenuId(),useType);
        if(null == baseMenuVO){
            return ServerResponse.createByErrorMessage("没有数据");
        }
        return ServerResponse.createBySuccess("查询成功",baseMenuVO);
    }
}
